/**
 * Created by Administrator on 2016/9/20 0020.
 */
var spider2 = require("../utils/spider2.js");
var BookInfo = require("../models/bookInfo.js");
var Chapter = require("../models/chapter.js");
var async = require("async");
var url = require("url");
var logger = require("../utils/myLog4.js");
//更新bookinfo，判断是否需要更新
function updateBookinfo(newBookinfo,oldBookinfo,callback){
    //获取需要更新的章节数
    var count = oldBookinfo.chapterList.length;
    var lack = newBookinfo.chapterList.length - count;
    if(lack > 0){
        //有新的章节，需要更新
        (new BookInfo(newBookinfo)).update(function(err,result){
            if(!err){
                result.chapterList = result.chapterList.slice(count,-1);
            }
            callback(err,result);
        });
    }else{
        //没有新章节，不需要更新
        logger.info("小说《"+oldBookinfo.bookName+"》无需更新");
        callback(null,null);
    }
}
function updateBook(url,callback){
    async.waterfall([
        function(cb){
            spider2.getChapterList(url,cb);
        },
        function(data,cb){
            var bookName = data.bookName;
            BookInfo.getBookByBookName(bookName,function(err,book){
                cb(err,data,book);
            });
        },
        function(data,book,cb){
            //如果该书未查询到（为录入数据库），则添加
            if(!book){
                logger.info("抓取到新的小说《"+data.bookName+"》,需要更新"+data.chapterList.length+"章");
                (new BookInfo(data)).save(function(err,result){
                    cb(err,result);
                });
            }else{
                //如果该书存在，则更新
                updateBookinfo(data,book,function(err,result){
                    cb(err,result);
                });
            }
        },
        function(data,cb){
            if(data){
                insertChapters(data,cb);
            }else{
                cb();
            }
        }
    ],function(err){
        callback(err);
    });
}
//存入章节列表
function insertChapters(data,callback){
    var webIndex = data.webIndex;
    async.eachLimit(data.chapterList,10,function(chapter,cb){
        chapter.bookName = data.bookName;
        insertChapter(data.bookName,webIndex,chapter,function(err){
            if(err){
                logger.error("更新小说《"+data.bookName+"》的【"+chapter.chapterName+"】章失败,href:"+chapter.chapterHref);
                logger.error("err"+err);
            }
            cb();
        });
    },function(){
        callback();
    });
}
//存入章节列表
function insertChapters(data,callback){
    var webIndex = data.webIndex;
    var i = 1;
    async.eachLimit(data.chapterList,2,function(chapter,cb){
        console.log(i++,data.bookName,chapter.chapterName);
        var cp = {
            "bookName":data.bookName,
            "bookId":data._id,
            "chapterName":chapter.chapterName,
            "chapterHref":chapter.chapterHref,
            "index":chapter.index
        }
        insertChapter(webIndex,cp,function(err){
            if(err){
                logger.error("更新小说《"+data.bookName+"》的【"+chapter.chapterName+"】章失败,href:"+chapter.chapterHref);
                logger.error("err"+err);
            }
            setImmediate(cb);
        });
    },function(){
        callback();
    });
}
//保存某一章节信息
function insertChapter(webIndex,chapter,callback){
    var chapterHref = url.resolve(webIndex,chapter.chapterHref);
    spider2.getChapter(chapterHref,function(err,result){
        if(err){
            callback(err);
        }else {
            chapter.chapterContent = result.chapterContent;
            (new Chapter(chapter)).save(callback);
        }
    });
}

function updateBooks(){
    spider2.getBookList(function(err,data){
        //data.books = data.books.slice(0,1);
        async.eachSeries(data.books,function(book,cb){
            var bookHref = book.bookHref;
            updateBook(bookHref,function(){
                cb();
            });
        },function(){
            logger.info("本次更新完毕");
        });
    });
}

exports.updateBooks = updateBooks;